<script setup lang="ts">
import { ref, onMounted, reactive, computed, watch } from "vue";
import { getDeviceConfigApi, setDeviceConfigApi } from '@/api/configs/deviceConfig';
import { useI18n } from "vue-i18n";
import { ElMessageBox, ElNotification } from "element-plus";
import { getProductAttributes } from "@/utils/appCommon/appCommonOptions/deviceParam";
import CopyDevices from './CopyDevices.vue';
import { formatTimestampToDatetime } from "@/utils/appCommon/timeUtil";

const emit = defineEmits(['onsubmit']);

const props = defineProps({
  params: {
    type: Object,
    required: true
  },
  deviceNo: {
    type: String,
    required: true
  },
  deviceOptions: {
    type: Array,
    required: false,
    default: [],
  },
  forceRefresh: {
    type: Number,
    required: false,
    default: 0
  }
});

// 定义模型接口
interface AeLevelRuleItem {
  prop: string;
  value: number;
}

interface AeLevelRule {
  items: AeLevelRuleItem[];
}

interface AeLevelStrength {
  level: number;
  rules: AeLevelRule[];
}

interface AeLevelActivity {
  level: number;
  times: number;
}

interface AeLevelConfig {
  enable: boolean;
  aeLevelStrength: AeLevelStrength[];
  aeLevelActivity: AeLevelActivity[];
  calTime: number;
  reportLevel: number;
  interval: number;
  updatetime?: number;
}

const i18n = useI18n();

const current = ref({
  configKey: "lv2",
  deviceNo: "",
  productId: 0,
  productKey: "",
  updatedAt: 0,
});

const loading = ref(false);
// 复制设备配置
const copyDevices = ref<string[]>([]);

// IoT参数选项
const iotParamOptions = ref([

]);

// 表单数据
const form = ref<AeLevelConfig>({
  enable: false,
  aeLevelStrength: [],
  aeLevelActivity: [],
  calTime: 0,
  reportLevel: 0,
  interval: 0,
});

// 监听props变化
watch(
  () => props,
  (newVal) => {
    current.value.updatedAt=0
    current.value.deviceNo = newVal.deviceNo;
    current.value.productId = newVal.params.productId;
    current.value.productKey = newVal.params.productKey;
    const attrs = getProductAttributes(current.value.productKey)
    // 将val从小驼峰转换为蛇形
    const transformedAttrs = attrs.map(attr => {
      // 小驼峰转蛇形：在大写字母前加下划线，然后转小写
      const snakeCaseVal = attr.val.replace(/([A-Z])/g, '_$1').toLowerCase();
      return {
        ...attr,
        val: snakeCaseVal
      };
    });
    iotParamOptions.value = transformedAttrs;

    setTimeout(async () => {
      await loadConfig();
    }, 0);
  },
  { deep: true, immediate: true }
);
// 加载配置
const loadConfig = async () => {
  try {
    loading.value = true;
    const res = await getDeviceConfigApi({
      deviceNo: current.value.deviceNo,
      configKey: current.value.configKey,
    });
    if (res.data?.configValue) {
      // 确保数据结构正确
      const config = JSON.parse(res.data?.configValue);
      form.value = {
        enable: config.enable || false,
        aeLevelStrength: config.aeLevelStrength || [],
        aeLevelActivity: config.aeLevelActivity || [],
        calTime: config.calTime || 0,
        reportLevel: config.reportLevel || 0,
        interval: config.interval || 0
      };
      form.value.updatetime =  res.data?.updatedAt
      // 更新当前时间戳
      if (form.value.updatetime) {
        current.value.updatedAt = form.value.updatetime;
      }
      // 确保强度和活度数组不为空，提供默认数据
      if (form.value.aeLevelStrength.length === 0) {
        addStrength();
      }
      if (form.value.aeLevelActivity.length === 0) {
        addActivity();
      }
    } else {
      // 初始化默认数据
      form.value = {
        enable: false,
        aeLevelStrength: [],
        aeLevelActivity: [],
        calTime: 0,
        reportLevel: 0,
        interval: 0
      };
    }
  } catch (error) {
    console.error('加载配置失败:', error);
  } finally {
    loading.value = false;
  }
};

// 保存配置
const saveConfig = async () => {
  try {
    loading.value = true;
    await setDeviceConfigApi({
      deviceNo: current.value.deviceNo,
      configKey: current.value.configKey,
      configValue: form.value,
      copyDevices: copyDevices.value
    });
    ElNotification.success({
      title: '成功',
      message: '配置保存成功'
    });
  } catch (error) {
    console.error('保存配置失败:', error);
    ElNotification.error({
      title: '错误',
      message: '保存配置失败'
    });
    throw error;
  } finally {
    loading.value = false;
  }
};

// 处理保存配置，添加二次确认
const handleSaveConfig = async () => {
  try {
    await ElMessageBox.confirm(
      i18n.t('buttons.tips.confirmSaveConfig') + "?",
      "",
      {
        confirmButtonText: i18n.t('buttons.confirm'),
        cancelButtonText: i18n.t('buttons.cancel'),
        type: 'warning'
      }
    );
    await saveConfig();

    // 重新加载配置以更新时间戳
    setTimeout(async ()=>{
      await loadConfig();
    },2000)

  } catch (error) {
    console.log('保存已取消');
  }
};

// 新增强度
const addStrength = () => {
  if (form.value.aeLevelStrength.length >= 4) {
    ElNotification.warning({
      title: '提示',
      message: '最多只能添加4个强度'
    });
    return;
  }

  const newLevel = Math.max(...form.value.aeLevelStrength.map(s => s.level), 0) + 1;
  form.value.aeLevelStrength.push({
    level: newLevel,
    rules: [{ items: [{ prop: "", value: 0 }] }]
  });
};

// 删除强度
const removeStrength = (index: number) => {
  if (form.value.aeLevelStrength.length <= 1) {
    ElNotification.warning({
      title: '提示',
      message: '至少保留一个强度配置'
    });
    return;
  }

  const oldLevelCount = form.value.aeLevelStrength.length;
  form.value.aeLevelStrength.splice(index, 1);

  // 重新排序等级
  form.value.aeLevelStrength.forEach((strength, idx) => {
    strength.level = idx + 1;
  });

  // 如果reportLevel超过了新的强度等级数，自动调整并提示用户
  if (form.value.reportLevel > form.value.aeLevelStrength.length) {
    const previousLevel = form.value.reportLevel;
    form.value.reportLevel = form.value.aeLevelStrength.length;

    // 只有在当前设置了上报级别且不等于0时才提示用户
    if (previousLevel > 0) {
      ElNotification.info({
        title: '提示',
        message: `由于强度等级从${oldLevelCount}个减少到${form.value.aeLevelStrength.length}个，上报级别已自动调整为${form.value.reportLevel}`
      });
    }
  }
};

// 新增规则
const addRule = (strengthIndex: number) => {
  form.value.aeLevelStrength[strengthIndex].rules.push({
    items: [{ prop: "", value: 0 }]
  });
};

// 删除规则
const removeRule = (strengthIndex: number, ruleIndex: number) => {
  if (form.value.aeLevelStrength[strengthIndex].rules.length <= 1) {
    ElNotification.warning({
      title: '提示',
      message: '至少保留一个规则'
    });
    return;
  }

  form.value.aeLevelStrength[strengthIndex].rules.splice(ruleIndex, 1);
};

// 新增参数项
const addRuleItem = (strengthIndex: number, ruleIndex: number) => {
  form.value.aeLevelStrength[strengthIndex].rules[ruleIndex].items.push({
    prop: "strength",
    value: 0
  });
};

// 删除参数项
const removeRuleItem = (strengthIndex: number, ruleIndex: number, itemIndex: number) => {
  if (form.value.aeLevelStrength[strengthIndex].rules[ruleIndex].items.length <= 1) {
    ElNotification.warning({
      title: '提示',
      message: '至少保留一个参数'
    });
    return;
  }

  form.value.aeLevelStrength[strengthIndex].rules[ruleIndex].items.splice(itemIndex, 1);
};

// 新增活度
const addActivity = () => {
  if (form.value.aeLevelActivity.length >= 9) {
    ElNotification.warning({
      title: '提示',
      message: '最多只能添加9个活度'
    });
    return;
  }

  const newLevel = Math.max(...form.value.aeLevelActivity.map(a => a.level), 0) + 1;
  form.value.aeLevelActivity.push({
    level: newLevel,
    times: 0
  });
};

// 删除活度
const removeActivity = (index: number) => {
  if (form.value.aeLevelActivity.length <= 1) {
    ElNotification.warning({
      title: '提示',
      message: '至少保留一个活度配置'
    });
    return;
  }

  form.value.aeLevelActivity.splice(index, 1);
  // 重新排序等级
  form.value.aeLevelActivity.forEach((activity, idx) => {
    activity.level = idx + 1;
  });
};

// 格式化系统时间
const systemTime = computed(() => {
  if (!current.value.updatedAt || current.value.updatedAt == 0) {
    return "-";
  }
  return formatTimestampToDatetime(current.value.updatedAt);
});

onMounted(() => {
  // 组件挂载时的初始化逻辑
});
</script>

<template>
  <div class="ae-level-config">
    <el-form :model="form" >
      <el-form-item :label="i18n.t('device.deviceNo')" prop="deviceNo">
        <el-input v-model="current.deviceNo" disabled />
      </el-form-item>

      <el-form-item :label="i18n.t('device.level.ratingEnable')" prop="enable">
        <el-radio-group v-model="form.enable">
          <el-radio :label="true">{{ i18n.t('buttons.yes') }}</el-radio>
          <el-radio :label="false">{{ i18n.t('buttons.no') }}</el-radio>
        </el-radio-group>
      </el-form-item>

      <!-- 强度配置 -->
      <el-form-item>
        <div style="display: flex; justify-content: space-between; align-items: center;">
          <h3>{{ i18n.t('device.level.strengthConfig') }}</h3>
          <el-button
            type="primary"
            size="small"
            @click="addStrength"
            :disabled="form.aeLevelStrength.length >= 4"
          >
            {{ i18n.t('buttons.add') }}
          </el-button>
        </div>

        <div v-for="(strength, strengthIndex) in form.aeLevelStrength" :key="strengthIndex" class="strength-item">
          <div class="strength-header">
            <h4>{{ i18n.t('device.level.strength') }} {{ strength.level }}</h4>
            <el-button
              type="danger"
              size="small"
              @click="removeStrength(strengthIndex)"
              :disabled="form.aeLevelStrength.length <= 1"
            >
              {{ i18n.t('buttons.delete') }}
            </el-button>
          </div>

          <!-- 规则列表 -->
          <div v-for="(rule, ruleIndex) in strength.rules" :key="ruleIndex" class="rule-item">
            <div class="rule-header">
              <span>{{ i18n.t('device.level.rule') }} {{ ruleIndex + 1 }}</span>
              <el-button
                type="primary"
                size="small"
                @click="addRuleItem(strengthIndex, ruleIndex)"
              >
                {{ i18n.t('device.level.addParam') }}
              </el-button>
              <el-button
                type="danger"
                size="small"
                @click="removeRule(strengthIndex, ruleIndex)"
                :disabled="strength.rules.length <= 1"
              >
                {{ i18n.t('buttons.delete') }}
              </el-button>
            </div>

            <!-- 参数项列表 -->
            <div v-for="(item, itemIndex) in rule.items" :key="itemIndex" class="param-item">
              <el-select
                v-model="item.prop"
                :placeholder="i18n.t('device.level.selectProp')"
                style="width: 150px; margin-right: 10px;"
              >
                <el-option
                  v-for="option in iotParamOptions"
                  :key="option.val"
                  :label="option.label+'('+option.unit+')'"
                  :value="option.val"
                />
              </el-select>
              <el-input-number
                v-model.number="item.value"
                :min="0"
                style="width: 150px; margin-right: 10px;"
              />
              <el-button
                type="danger"
                size="small"
                @click="removeRuleItem(strengthIndex, ruleIndex, itemIndex)"
                :disabled="rule.items.length <= 1"
              >
                {{ i18n.t('buttons.delete') }}
              </el-button>
            </div>
          </div>

          <el-button
            type="primary"
            size="small"
            @click="addRule(strengthIndex)"
            style="margin-top: 10px;"
          >
            {{ i18n.t('device.level.addRule') }}
          </el-button>
        </div>
      </el-form-item>

      <!-- 活度配置 -->
      <el-form-item>
        <div style="display: flex; justify-content: space-between; align-items: center;">
          <h3>{{ i18n.t('device.level.activityConfig') }}</h3>
          <el-button
            type="primary"
            size="small"
            @click="addActivity"
            :disabled="form.aeLevelActivity.length >= 9"
          >
            {{ i18n.t('buttons.add') }}
          </el-button>
        </div>

        <div v-for="(activity, index) in form.aeLevelActivity" :key="index" class="activity-item">
          <el-form-item :label="i18n.t('device.level.level') + ' ' + activity.level">
            <div style="display: flex; align-items: center;">
              <el-input-number
                v-model.number="activity.times"
                :min="0"
                style="width: 200px; margin-right: 10px;"
                :label="i18n.t('device.level.times')"
              />
              <el-button
                type="danger"
                size="small"
                @click="removeActivity(index)"
                :disabled="form.aeLevelActivity.length <= 1"
              >
                {{ i18n.t('buttons.delete') }}
              </el-button>
            </div>
          </el-form-item>
        </div>
      </el-form-item>

      <el-form-item :label="i18n.t('device.level.LEVEL_TIME') + '(s)'" prop="calTime">
        <el-input-number v-model.number="form.calTime" :min="0" style="min-width: 200px;" />
      </el-form-item>

      <el-form-item :label="i18n.t('device.level.LEVEL_STRENGTH_REPORT_TYPE')" prop="reportLevel">
        <el-input-number
          v-model.number="form.reportLevel"
          :min="0"
          :max="form.aeLevelStrength.length"
          style="min-width: 200px;"
          :step="1"
          clearable
          :placeholder="`0-${form.aeLevelStrength.length}`"
        />
        <div class="form-hint">
          tips:(0-{{ form.aeLevelStrength.length }})
        </div>
      </el-form-item>

      <el-form-item :label="i18n.t('device.level.LEVEL_STRENGTH_REPORT_INTERVAL') + '(s)'" prop="interval">
        <el-input-number v-model.number="form.interval" :min="0" style="min-width: 200px;" />
      </el-form-item>
      <!-- 系统时间 -->
      <el-form-item :label="i18n.t('device.aeparam.SYSTEM_TIME')">
        <el-input v-model="systemTime" type="text" disabled style="width: 100%; max-width: 300px;" />
      </el-form-item>
      <!-- 复制设备配置 -->
      <el-form-item :label="i18n.t('device.copyDevices.title')">
        <CopyDevices
          :device-no="current.deviceNo"
          v-model="copyDevices"
        />
      </el-form-item>

      <el-form-item>
        <el-button type="primary" :loading="loading" @click="handleSaveConfig" style="min-width: 150px;">
          {{ i18n.t('buttons.submit') }}
        </el-button>
      </el-form-item>
    </el-form>
  </div>
</template>

<style scoped>
.ae-level-config {
  padding: 20px;
  overflow-x: auto;
}

.strength-item {
  border: 1px solid #e4e7ed;
  border-radius: 4px;
  padding: 15px;
  margin-bottom: 20px;
  margin-right: 10px;
  background-color: #fafafa;
}

.strength-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 15px;
}

.rule-item {
  border: 1px solid #dcdfe6;
  border-radius: 4px;
  padding: 10px;
  margin-bottom: 10px;
  background-color: #ffffff;
}

.rule-header {
  display: flex;
  align-items: center;
  margin-bottom: 10px;
  gap: 10px;
}

.param-item {
  display: flex;
  align-items: center;
  margin-bottom: 8px;
  padding-left: 20px;
}

.activity-item {
  margin-bottom: 10px;
  margin-right: 10px;
}

h3, h4 {
  margin: 0 0 10px 0;
  color: #303133;
}
.form-hint {
  color: #909399;
  font-size: 12px;
  margin-top: 4px;
}
</style>
